package org.gap.wizards.world.builder;

import java.awt.Dimension;
import java.awt.Point;

import org.gap.wizards.Start;

public class LabyrinthFactory extends MapBase {
	private static LabyrinthFactory factory = new LabyrinthFactory();
	
	public static char[][] createMap(int width, int height, int numberOfRooms) {
		factory.initialize();
		factory.build(width, height, numberOfRooms);
		
		return factory.theMap;
	}
	
	private void build(int width, int height, int numberOfRooms) {
		fillMap(width, height);
		
		// 1. Select a starting point, length, and direction
		Point start = new Point(width / 2, height / 2); 
		int length; Direction dir;
		do {
			length = generateLength();
			dir = generateDirection();
			
			//  2. check for validity, if not return to 1.
		} while (!check(start, length, dir));
		draw(start, length, dir);
		theMap[start.y][start.x] = '@';
		// 3. Add a room
		while (numberOfRooms > 0) {
			Dimension dimension = generateRoom();
			Wall wall = generateWall();
			if (wall != null)
				while (!check(wall.start(), dimension, wall.facing())) {
					wall = generateWall();
					dimension = generateRoom();
					if (wall == null)
						break;
				}
			if (wall != null) {
				draw(wall.start(), dimension, wall.facing());
				usedWall(wall);
				numberOfRooms--;
			} else {
				usedWall(null);
			}
			// 4. Add a hall (maybe)
			wall = generateWall();
			if (wall != null)
				while (!check(wall.start(), length, wall.facing())) {
					wall = generateWall();
					if (wall == null)
						break;
					length = generateLength();			
				} 
			if (wall != null) {
				draw(wall.start(), length, wall.facing());
				usedWall(wall);
			}
			else {
				numberOfRooms--;
				usedWall(wall);
			}
		}
	}
	
	public static void main(String[] args) {
		LabyrinthFactory.createMap(Start.SCREEN_WIDTH, Start.SCREEN_HEIGHT, 10);
		factory.drawMap();
	}
}
